﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AODL.Document;
using AODL.Document.TextDocuments;
using AODL.Document.Content.Text;
using AODL.Document.Styles;
using System.Collections;

namespace _2escribirodt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /* CODIGO PARA ESCRIBIR UN ODT
            TextDocument doc = new TextDocument();
            doc.New();
            
            Paragraph p = new Paragraph(doc);
            IText text = new SimpleText(doc,textBox1.Text); 
            p.TextContent.Add(text);
            
            doc.Content.Add(p);
            doc.SaveTo("C:\\Users\\Andres Lester\\Desktop\\a.odt");
             * */

            txBinary.Text = String.Empty;

            string strText = textBox1.Text;

            byte[] btText;
            btText = System.Text.Encoding.UTF8.GetBytes(strText);
            Array.Reverse(btText);
            BitArray bit = new BitArray(btText);
            StringBuilder sb = new StringBuilder();


            for (int i = bit.Length - 1; i >= 0; i--)
            {
                if (bit[i] == true)
                {
                    sb.Append(1);
                }
                else
                {
                    sb.Append(0);
                }
            }


            txBinary.Text = sb.ToString();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            txTraducion.Text = String.Empty;

            string str = txBinary.Text;
            BitArray bit = new BitArray(str.Length);
            for (int i = 0; i < str.Length; i++)
            {
                if (str.Substring(i, 1) == "1")
                {
                    bit[i] = true;
                }
                else
                {
                    bit[i] = false;
                }
            }


            int numBytes = bit.Count / 8;
            if (bit.Count % 8 != 0) numBytes++;


            byte[] bytes = new byte[numBytes];
            int byteIndex = 0, bitIndex = 0;


            for (int i = 0; i < bit.Count; i++)
            {
                if (bit[i])
                    bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));


                bitIndex++;
                if (bitIndex == 8)
                {
                    bitIndex = 0;
                    byteIndex++;
                }
            }

            txTraducion.Text = System.Text.Encoding.UTF8.GetString(bytes);
        }
    }
}
